package com.example.tests;

import static org.apache.commons.lang3.RandomStringUtils.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.openqa.selenium.By;
import org.testng.annotations.DataProvider;

import com.example.framework.ApplicationManager;
import com.example.objects.ContactObject;

public class ContactDataGenerator {
	
	Random rnd = new Random();
	private static ApplicationManager app;
	
	public static void main(String[] args) throws Exception {
		if (args.length < 2) {
			System.out.println("Specify two parameters: fileName and contactsCount");
			return;
		}
		String file = args[0];
		int count = Integer.parseInt(args[1]);
		
		app = new ApplicationManager();
		Properties props = new Properties();
		props.load(new FileReader("application.properties"));
		app.setProperties(props);
		
		try {
			new ContactDataGenerator().generateDataToFile(file, count);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@DataProvider(name = "randomContacts")
	public static Iterator<Object[]> generateRandomContacts() throws Exception {
		List<ContactObject> contacts = new ContactDataGenerator().generateRandomContactList(5);
		List<Object[]> list = new ArrayList<Object[]>();
		for (ContactObject contact : contacts) {
			list.add(new Object[]{contact});
		}
		return list.iterator();
	}
	
	@DataProvider(name = "contactsFromFile")
	public static Iterator<Object[]> loadContactsFromFile() throws IOException {
		
		List<Object[]> list = new ArrayList<Object[]>();
		String fileName = app.getInstance().getProperty("contactFile");
		BufferedReader reader = new BufferedReader(new FileReader(fileName));
		String line = reader.readLine();
		while (line != null) {
			String[] parts = line.split("\t");
			ContactObject contact = new ContactObject()
			.setFirstName(parts[0])
			.setLastName(parts[1])
			.setAddress(parts[2])
			.setPhoneHome(parts[3])
			.setPhoneMobile(parts[4])
			.setPhoneWork(parts[5])
			.setEmailPrimary(parts[6])
			.setEmailSecondary(parts[7])
			.setBdayDay(parts[8])
			.setBdayMonth(parts[9])
			.setBdayYear(parts[10])
			.setGroupByIndex(Integer.parseInt(parts[11])) //if I user ParseInt(parts[11]) test selects empty value
			.setAddressSecondary(parts[12])
			.setPhoneSecondary(parts[13]);
			list.add(new Object[]{contact});
			line = reader.readLine();
		}
		return list.iterator();
	}
	
	private void generateDataToFile(String fileName, int count) throws Exception {		
		List<ContactObject> contacts = generateRandomContactList(count);
		File file = new File(fileName);
		if (file.exists()) {
			file.delete();
		}
		FileWriter writer = new FileWriter(file);
		for (ContactObject contact : contacts) {
			writer.write(
					  contact.firstName 		+ "\t" + contact.lastName 		+ "\t"
					+ contact.address 			+ "\t" + contact.phoneHome 		+ "\t"
					+ contact.phoneMobile 		+ "\t" + contact.phoneWork 		+ "\t"
					+ contact.emailPrimary 		+ "\t" + contact.emailSecondary + "\t"
					+ contact.bdayDay 			+ "\t" + contact.bdayMonth 		+ "\t"
					+ contact.bdayYear 			+ "\t" + contact.groupByIndex 	+ "\t"
					+ contact.addressSecondary  + "\t" + contact.phoneSecondary + "\t"
					+ "\n"
					);
		}
		writer.close();
		app.stop();
	}
	
	private List<ContactObject> generateRandomContactList(int count) throws Exception {	
		List<ContactObject> list = new ArrayList<ContactObject>();
		for (int i =0; i<count; i++) {
			ContactObject contact = new ContactObject()
			.setFirstName("name" + randomAlphabetic(5))
			.setLastName(randomAlphabetic(10))
			.setAddress("street" + randomNumeric(3))
			.setPhoneHome(randomNumeric(10))
			.setPhoneMobile(randomNumeric(10))
			.setPhoneWork(randomNumeric(10))
			.setEmailPrimary("em@il" + rnd.nextInt() + ".com")
			.setEmailSecondary(randomAlphanumeric(5) + "@" + randomAlphabetic(5) + "." + randomAlphabetic(3))
			.setBdayDay(getRandomDay(31))
			.setBdayMonth(getRandomMonth())
			.setBdayYear(getRandomYear(1950, 2012))
			.setGroupByIndex(getRandomGroup())
			.setAddressSecondary("addr" + randomAlphanumeric(10))
			.setPhoneSecondary(randomNumeric(10));
			
			list.add(contact);
		}
		return list;
	}
	
	String[] MONTHS = new String[] { "January", "February",
			"March", "April", "May", "June", "July", "August", "September",
			"October", "November", "December" };
	
	public int generateRandomNumberBetween(int start, int end) {
		int interval = end - start;
		int out = new Random().nextInt(Math.abs(interval));
		return interval>0?(out + start):(out + end);
	}
	
	public String getRandomMonth() {
		return MONTHS[rnd.nextInt(12)];
	}
	
	public String getRandomDay(int daysInMonth) {
		return Integer.toString((generateRandomNumberBetween(1, daysInMonth))); 
	}
	
	public String getRandomYear(int startYear, int endYear) {
		return Integer.toString((generateRandomNumberBetween(startYear, endYear))); 
	}
	
	public int getRandomGroup() throws Exception {	
        int numberOfGroupsInGroupPage = app.getGroupHelper().getGroups().size();
        app.getNavigationHelper().openMainPage();
        int numberOfGroupsInHomePage = app.getContactHelper().getNumberOfElementsInDropDownList(By.name("to_group"));
        int numberOfGroups = 0;

		if (numberOfGroupsInGroupPage == numberOfGroupsInHomePage) {
			numberOfGroups  = numberOfGroupsInGroupPage;
		} else {
			throw new Exception("Group quantity doesn't match. Need to rebuild groupCache!");
		}
		if (numberOfGroups == 0) {
			throw new Exception("There are no groups. Nothing to select!");
		} else {
			return rnd.nextInt(numberOfGroups);
		}		
	}


}
